"ui";
//禁止重复运行
engines.all().map((ScriptEngine) => {
    //log(engines.myEngine().toString(),ScriptEngine.toString())
    if (engines.myEngine().toString() !== ScriptEngine.toString()) {
    ScriptEngine.forceStop();
    }
});
try {
    if (!$floaty.checkPermission()) {
        toastLog("本脚本需要悬浮窗权限来显示悬浮窗，请在随后的界面中允许并重新运行本脚本。");
        sleep(5000)
        $floaty.requestPermission();
        exit();
    }
} catch (e) {
    //toastLog(e)
}
importClass(android.util.Base64)
importClass(android.content.res.ColorStateList)
importClass(android.view.View)
importClass(android.graphics.drawable.GradientDrawable);
importClass(java.io.FileOutputStream);
importClass(android.graphics.Color);

let MLKitOCR = $plugins.load('org.autojs.autojspro.plugin.mlkit.ocr');
ocr = new MLKitOCR();
//ocr = $plugins.load("com.hraps.ocr");
require('./解除autojsPro限制.js') 
sm = "本软件完全免费 且仅供技术学习交流,请勿用于商业及非法用途,如产生法律纠纷与本脚本作者无关,当您使用本脚本时,说明您已经同意并接受本协议";
ScriptRunning = false
var 配置 = storages.create("DYds");
var IMEI = storages.create("IMEI");
Data = storages.create("Sun3个晒@897738591");
mCachePath = Data.get("mCachePath", "/sdcard/Pictures/result")
gPath = Data.get("gPath", "/sdcard/评语.txt")
gPass = Data.get("gPass", "")
ip_adress = Data.get("ip_adress", "")
gTaskPath =  Data.get("gTaskPath", "")
gLocalset = Data.get("gLocalset", false)
gLocalReceipt = Data.get("gLocalReceipt", false)
gPassword = Data.get("gPassword", "")
glinePath = Data.get("glinePath", "")
gLocalpay = Data.get("gLocalpay", false)
gLocalpays = Data.get("gLocalpays", false)
gLocaladd = Data.get("gLocaladd", false)
gLocaltaobao = Data.get("gLocaltaobao", false)
gLocallitetao = Data.get("gLocallitetao", false)
mOpenC = Data.get("mOpenC", false)
remarks =  Data.get("remarks", "")
gpaysNum =  Data.get("gpaysNum", "")
//购物车当前数量
gmSuccess = Data.get("gmSuccess", 0)

global.mThreadObj = threads.start(function () { });
global.mTC_ThreadObj = threads.start(function () { });
global.mHeardThreadObj = threads.start(function () { });
global.glastitemView = null
let LoginModule = require("./login.js");
ui.statusBarColor("#2F4F4F");
var version = app.versionName

ui.layout(
    <frame>
        {/* 登录页面容器 */}
        <frame id="loginContainer">
        </frame>
    <vertical id="mainContainer" visibility="gone" bg="#F5F5F5">
         <appbar bg="#2F4F4F" >
            <frame h="35">
                <card   w="50" h="36" cardCornerRadius="15" cardBackgroundColor="#CC3333" layout_gravity="center|left"> 
                <button id="exitbut" text="退出" textSize="12sp"   bg="#CC3333" textColor="#ffffff" />
                </card>
                <text id="title" textSize="18sp"  textColor="white" textStyle="bold" gravity="center" />
                <toolbar id="toolbar" />
                <Switch textSize="12sp" w="auto" id="autoService"  textColor="white" checked="{{auto.service != null}}" layout_gravity="center|right" paddingRight="10" />
            </frame>
            <tabs id="tabs" h="40" bg="#2F4F4F" tabIndicatorColor="#FFFFFF" />
        </appbar>
        <vertical gravity="center|bottom"  >
                <TextView id="ad2" textSize="15sp" paddingBottom="5" singleLine="true" ellipsize="marquee" gravity="center|bottom" focusable="true" text="{{sm}}" textColor="#2F4F4F" />
                </vertical>
        <viewpager id="viewpager">
            
            <vertical paddingLeft="3" paddingRight="3">
             
                <card w="*" h="40" cardBackgroundColor="#000000" margin="10 1 10 1" cardElevation="1dp" gravity="center_vertical" alpha="1" cardCornerRadius="3dp">
                <card w="*" h="36"  cardCornerRadius="2dp" margin="2" cardElevation="1dp" gravity="center_vertical" alpha="1" cardCornerRadius="1">
                    
                    <linear orientation="horizontal" gravity="center">
                        
                            <Switch id="autoignoring" text="电池优化" layout_gravity="center|right" checked="{{$power_manager.isIgnoringBatteryOptimizations()}}" padding="8" textSize="15sp" />
                            <Switch id="autoforeground" text="前台服务" layout_gravity="center|right" checked="{{$settings.isEnabled('foreground_service')}}" padding="8" textSize="15sp" />
                        
                    </linear>
                    
                </card>
                </card>

                <vertical>
                    <card w="*" h="*" margin="10 8" cardCornerRadius="6dp" 
                            cardElevation="2dp" gravity="center">  
                                <vertical padding="5 4"  gravity="center">
                            
                                <input id="ip_adress" w="auto"   gravity="center" textSize="15sp" hint="请输入服务器地址 0.0.0.0" text="{{ip_adress}}"/>
                            
                            </vertical>          
                    </card>
                </vertical>

                <frame>   
                    <vertical margin="10"> 
                    <horizontal padding="10 -8 8 0">
                                <text text="编号:" textSize="18sp" textColor="black"  />
                                <input id="remarks" textSize="48sp" textColor="red" gravity="center"  w="auto" minWidth="100" text="{{remarks}}"/>
                    </horizontal>

                    </vertical>
                </frame>
          
                <text text="   注意事项：" gravity="left" textColor="#FF8C00" />
                <text text="   1.请手机使用淘宝10.15.30版本," gravity="left" />
                <text text="   2.本软件需要无障碍权限和悬浮窗权限," gravity="left" />
                <text text="   3.请自行开启以上权限。" gravity="left" />
                
                <linear  gravity="center">
                <button id="start" text="▶" w="250" style="Widget.AppCompat.Button.Colored" visibility="gone"/>

                </linear>
                
                {/* 添加退出登录按钮 */}
                <linear gravity="center" margin="0 10 0 0">
                    <button id="logoutBtn" text="退出登录" w="250" style="Widget.AppCompat.Button.Colored"/>
                </linear>
            
                       
            </vertical>
            
            <vertical paddingLeft="3" paddingRight="3">
            <checkbox id="mStart" textSize="14sp"  text="隐藏悬浮按钮" gravity="center|left" />
            <linear >
            <checkbox id="mOpenC" textSize="14sp"  text="悬浮日志" gravity="center|left" />
            <frame layout_weight="1"></frame> {/* <!-- 这个空白视图将向右推动卡片 --> */}

            
            <frame  padding="10">
                <card w="*" h="*" cardBackgroundColor="#000000" margin="10 1 10 1" cardElevation="1dp" gravity="center_vertical" alpha="1" cardCornerRadius="3dp">
                    <card w="*" h="*"  cardCornerRadius="2dp" margin="2" cardElevation="1dp" gravity="center_vertical" alpha="1" cardCornerRadius="1">
                        
                        <linear orientation="horizontal">
                            <text id="OpenDebugger"  w="auto" textColor="#222222" textSize="14sp" padding= "10 0" text="打开日志" />
                        </linear>
                        
                    </card>
                </card>
            </frame>
            
            </linear>
            <linear > 
            <checkbox id="gLocaltaobao" textSize="14sp" checked="{{gLocaltaobao}}"  text="淘宝" gravity="center|left" />
            <checkbox id="gLocallitetao" textSize="14sp" checked="{{gLocallitetao}}"  text="淘特" gravity="center|left" />
            </linear>
            <frame>{/* 横线布局 */}
                <horizontal padding="8">
                <View h="1" bg="#CCCCCC" layout_gravity="center_horizontal"/>
                </horizontal>
            </frame> 
            <vertical>
                <card w="*" h="*" margin="10 8" cardCornerRadius="6dp" 
                        cardElevation="2dp" gravity="center">  
                        <vertical padding="5 4">
                        
                        <linear>
                        <text id="mPath" w="auto" marginLeft="10" textColor="#222222" textSize="14sp"  text="支付密码:" />
                        <input id="gPassword"  marginLeft="10" w="100" gravity="center" textSize="15sp"  />
                        </linear>   
                        </vertical>          
                </card>
            </vertical>
            <vertical >
          
                <text text="选择任务类型"/>
                <radiogroup id="radiogroup1" orientation = "horizontal"  >
                    <radio id="radio1"  text="全部选中"/>
                    <radio id="radio2" text="循环收货"/>
                    <radio id="radio3" text="无痕刷单"/>
                    <radio id="radio4" text="任务四"/>
                </radiogroup>
                <linear > 
                    <text id="mPath" w="auto" marginLeft="10" textColor="#222222" textSize="14sp"  text="收货随机等待[ " />
                    <input id="randomMin"  marginLeft="10" minWith="100px" gravity="center" textSize="15sp"  text=""/>
                    <text id="mPath" w="auto" marginLeft="10" textColor="#222222" textSize="14sp"  text=" ] 到 [" />
                    <input id="randomMax"  marginLeft="10" minWith="100px" gravity="center" textSize="15sp"  text=""/>         
                    <text id="mPath" w="auto" marginLeft="10" textColor="#222222" textSize="14sp"  text=" ]秒" />
                </linear>
            </vertical>
            <vertical visibility="gone">
            <vertical  layout_width="match_parent" layout_height="wrap_content"  >
               <card    > 
                   <linear gravity="right">
                   <button id="删除记录"  textSize="10dp" textColor="#000000" style="Widget.AppCompat.Button.Colored" text='删除记录'/>
                   <button id="清空记录"  textSize="10dp" textColor="#000000" style="Widget.AppCompat.Button.Colored" text='清空记录'/>
                   </linear>
               </card>
               <card> 
                    
                   <scroll>
                   
                       <list id='todoList' >
                           <frame id='parent' >
                                <frame>{/* 横线布局 */}
                                    <horizontal >
                                    <View h="1" bg="#000000" layout_gravity="center_horizontal"/>
                                    </horizontal>
                                </frame> 
                               <linear>
                               <text textSize='20sp' w="200"  maxLines="1" textColor="#000000" text='{{this.content}}  '></text>
                               <text textSize='15sp' w="60"  maxLines="1" textColor="#000000" text='{{this.state}}  '></text>
                               <text textSize='12sp' maxLines="1"  textColor="#000000" text='{{this.time}}'></text>
                               </linear>
                          
                           </frame>
                       </list>
                </scroll>
               </card>
         
          </vertical>
            
            </vertical>
           <vertical visibility="gone">
            <linear > 
            <checkbox id="gLocaltaobao" textSize="14sp" checked="{{gLocaltaobao}}"  text="淘宝" gravity="center|left" />
            <checkbox id="gLocallitetao" textSize="14sp" checked="{{gLocallitetao}}"  text="淘特" gravity="center|left" />
            </linear>

            <text textSize="20sp" gravity="center" text="= = = = = = = = = = = = = = = = = = = = = ="/>
            <linear > 
            <checkbox id="gLocaladd" textSize="14sp" checked="{{gLocaladd}}"  text="加购物车" gravity="center|left" />
            <checkbox id="gLocalpay" textSize="14sp" checked="{{gLocalpay}}"  text="单个付款" gravity="center|left" />
            <checkbox id="gLocalpays" textSize="14sp" checked="{{gLocalpays}}"  text="合并付款" gravity="center|left" />
            <input id="gpaysNum"  marginLeft="10" minWith="80" gravity="center" textSize="15sp"  text="{{gpaysNum}}"/>
            </linear>
           
            <vertical>
                <card w="*" h="*" margin="10 8" cardCornerRadius="6dp" 
                        cardElevation="2dp" gravity="center">  
                            <vertical padding="5 4">
                            <linear>
                        <text id="mPath" w="auto" marginLeft="10" textColor="#222222" textSize="14sp"  text="文件路径:" />
                        </linear>   
                        <input id="glinePath"  marginLeft="10" minWith="80" gravity="center" textSize="15sp"  text="{{glinePath}}"/>
                        <linear>
                        <text id="mPath" w="auto" marginLeft="10" textColor="#222222" textSize="14sp"  text="支付密码:" />
                     
                        </linear>   
                        </vertical>          
                </card>
            </vertical>
            </vertical>
            
            <vertical visibility="gone">
            <checkbox id="gLocalReceipt" textSize="14sp" checked="{{gLocalReceipt}}"  text="收货评价" gravity="center|left" />
            <vertical>
                <card w="*" h="*" margin="10 8" cardCornerRadius="6dp" 
                        cardElevation="2dp" gravity="center">  
                            <vertical padding="5 4">
                            <linear>
                        <text id="mPath" w="auto" marginLeft="10" textColor="#222222" textSize="14sp"  text="评论文件路径:" />
                        </linear>   
                        <input id="gPath"  marginLeft="10" minWith="80" gravity="center" textSize="15sp"  text="{{gPath}}"/>
                        </vertical>          
                </card>
            </vertical>
            <checkbox id="gLocalset" textSize="14sp" checked="{{gLocalset}}"  text="使用本地配置" gravity="center|left" />
            <vertical>
                <card w="*" h="*" margin="10 8" cardCornerRadius="6dp" 
                        cardElevation="2dp" gravity="center">  
                            <vertical padding="5 4">
                            <linear>
                        <text id="mCache" w="auto" marginLeft="10" textColor="#222222" textSize="14sp"  text="输出文件路径:" />
                        <frame>
                            <card w="*" h="*" cardBackgroundColor="#000000" margin="10 1 10 1" cardElevation="1dp" gravity="center_vertical" alpha="1" cardCornerRadius="3dp">
                                <card w="*" h="*"  cardCornerRadius="2dp" margin="2" cardElevation="1dp" gravity="center_vertical" alpha="1" cardCornerRadius="1">
                                    
                                    <linear orientation="horizontal">
                                        <text id="clear"  w="auto" textColor="#222222" textSize="14sp" padding= "10 0" text="清除任务记录" />
                                    </linear>
                                    
                                </card>
                            </card>
                        </frame>
                        </linear>   
                        <input id="mCachePath"  marginLeft="10" minWith="80" gravity="center" textSize="15sp"  text="{{mCachePath}}"/>
                        </vertical>          
                </card>
            </vertical>
            <vertical>
                    <card w="*" h="*" margin="10 8" cardCornerRadius="6dp" 
                            cardElevation="2dp" gravity="center">  
                            <vertical padding="5 4"  gravity="center">
                                <linear>
                                <text id="task" w="auto" textColor="#222222" textSize="14sp" text="任务链接:" />
                                </linear>
                                <horizontal>
                                
                                <input id="gTaskPath"   gravity="center|bottom" textSize="15sp" hint="请填入链接(一行一条)" minWidth="500" lines="8"  text="{{gTaskPath}}"/>
                                
                                </horizontal>
                            
                            </vertical>          
                    </card>
                </vertical>
            
                
            </vertical>

            </vertical>
          
                
                
        </viewpager>
      
         

            

    </vertical>
    </frame>
);

// 添加全局变量用于控制悬浮窗显示状态
global.mXFvisible = LoginModule.checkLoginStatus(); // 初始化为当前登录状态

// 初始化登录界面
function initLogin() {
    // 清空登录容器中的所有视图
    ui.loginContainer.removeAllViews();
    
    // 确保登录视图没有父视图
    try {
        let parent = LoginModule.loginView.getParent();
        if (parent != null) {
            parent.removeView(LoginModule.loginView);
        }
    } catch (e) {
        log("移除视图父级时出错: " + e);
    }
    
    // 将登录视图添加到容器中
    ui.loginContainer.addView(LoginModule.loginView);
    
    // 初始化登录页面
    LoginModule.initLoginPage(function(success) {
        if (success) {
            // 登录成功后切换到主界面
            ui.loginContainer.setVisibility(View.GONE);
            ui.mainContainer.setVisibility(View.VISIBLE);
            
            // 登录成功，强制显示悬浮窗
            global.mXFvisible = true;
            
            // 关闭现有悬浮窗（如果有）
            floaty.closeAll();
            
            // 强制mStart复选框不选中
            ui.mStart.checked = false;
            
            // 延迟100毫秒后显示悬浮窗，确保UI更新完成
            setTimeout(function() {
                if (!global.mXF_ThreadObj || !global.mXF_ThreadObj.isAlive()) {
                    xf();
                }
            }, 100);
            
            // 初始化主界面
            initMainPage();
        }
    });
}

// 初始化主界面函数
function initMainPage() {
    // 这里添加主界面初始化逻辑
    log("主界面初始化成功");
    // 可以在这里添加主界面的初始化代码
    // 如加载数据、设置UI元素状态等
}

// 检查登录状态
function checkLoginStatus() {
    if (LoginModule.checkLoginStatus()) {
        ui.loginContainer.setVisibility(View.GONE);
        ui.mainContainer.setVisibility(View.VISIBLE);
        
        // 已登录，强制显示悬浮窗
        global.mXFvisible = true;
        
        // 强制mStart复选框不选中
        ui.mStart.checked = false;
        
        // 延迟100毫秒后显示悬浮窗，确保UI更新完成
        setTimeout(function() {
            // 确保悬浮窗已经显示
            if (!global.mXF_ThreadObj || !global.mXF_ThreadObj.isAlive()) {
                // 关闭现有悬浮窗（如果有）
                floaty.closeAll();
                xf();
            }
        }, 100);
        
        // 初始化主界面
        initMainPage();
    } else {
        // 未登录，隐藏悬浮窗
        global.mXFvisible = false;
        // 关闭所有悬浮窗
        floaty.closeAll();
        initLogin();
    }
}
// 在原有的退出按钮点击事件中添加登出功能
ui.exitbut.click(function () {
    // 直接退出应用
    exit();
});

// 添加退出登录按钮的点击事件
ui.logoutBtn.click(function () {
    dialogs.confirm("确认退出", "是否退出登录？", function(confirm) {
        if (confirm) {
            LoginModule.logout();
            // 退出登录时隐藏悬浮窗
            global.mXFvisible = false;
            floaty.closeAll();
            ui.mainContainer.setVisibility(View.GONE);
            ui.loginContainer.setVisibility(View.VISIBLE);
            initLogin();
        }
    });
});

ui.title.text("TB tomato" + version);
ui.viewpager.setTitles(["云控配置", "本地配置"]);
ui.tabs.setupWithViewPager(ui.viewpager);
readconfig();

ui.ad2.setSelected(true);

ui.autoService.on("check", function (checked) {
  if (checked && auto.service == null) {
      app.startActivity({
          action: "android.settings.ACCESSIBILITY_SETTINGS"
      });
  }
  if (!checked && auto.service != null) {
      auto.service.disableSelf();
  }
});
ui.emitter.on("resume", function () {
  ui.autoService.checked = auto.service != null;
});
ui.emitter.on('back_pressed', function (event) {
    event.consumed = true;
});
ui.clear.click(function () { 
    dialogs.build({
        title: "",
        content: "    是否清除任务记录",
    
        negative: "取消",
        neutral: "确定"
    })
        .on("neutral", clearTask)
       
        .show();
        function clearTask(){
            let mCachePath
            mCachePath = ui.mCachePath.text()
            log(mCachePath)
            if(files.isDir(mCachePath)){
                files.removeDir(mCachePath+"/")
                toast("清除完成!")
               
            }else{
                toast("路径不存在")
            }
        }
    
 })
ui.gLocaltaobao.click( function (event) {
    if(ui.gLocaltaobao.checked){
        ui.gLocallitetao.checked = false
    }
});
ui.gLocallitetao.click( function (event) {
    if(ui.gLocallitetao.checked){
        ui.gLocaltaobao.checked = false
    }
});
ui.gLocaladd.click( function (event) {
    if(ui.gLocaladd.checked){
        ui.gLocalpay.checked = false
        ui.gLocalpays.checked = false
    }
});
ui.gLocalpay.click( function (event) {
    if(ui.gLocalpay.checked){
        ui.gLocaladd.checked = false
        ui.gLocalpays.checked = false
    }
});
ui.gLocalpays.click( function (event) {
    if(ui.gLocalpays.checked){
        ui.gLocaladd.checked = false
        ui.gLocalpay.checked = false
    }
});
 
ui.mOpenC.on("click",() => {
    if(ui.mOpenC.checked){
        Maple.ConSole();
        for(let i =0;i<15;i++){
            log("")
        }
    }else{
        Maple.close();
        
    }

})
ui.OpenDebugger.on("click",() => {
    app.startActivity("console");

})
ui.删除记录.on("click",() => {
    log(lastIndex)
    if(lastIndex || lastIndex == 0){
        dialogs.build({
            title: "",
            content: "    是否删除选中链接",
        
            negative: "取消",
            neutral: "确定"
            })
            .on("neutral", deleteMsg)
        
            .show();
           
    }
    function deleteMsg(){
        
        let mCachePath
        mCachePath = "/sdcard/Pictures/task"
        todoList.splice(lastIndex,1)
        ui.todoList.setDataSource(todoList);
        try {
            if(lastitemView){
                lastitemView.attr("bg","#ffffff") 
                lastitemView = null
            }
        } catch (error) {
            
        }
        lastIndex = null
        clearTask()
        for (let i = 0; i < todoList.length; i++) {
            saveText("/sdcard/Pictures/task/task.txt",todoList[i].content+"|"+todoList[i].state+"|"+todoList[i].time)
            
        }
        function saveText(path,message){
            if(!files.isFile(path) ){
                files.createWithDirs(path)
            }
            files.append(path, message+"\n")
          
        }
        function clearTask(){
            let mCachePath
            mCachePath = "/sdcard/Pictures/task"
         
            if(files.isDir(mCachePath)){
                files.removeDir(mCachePath+"/")
            }
        }
    }

})
ui.清空记录.on("click",() => {
    dialogs.build({
        title: "",
        content: "    是否清空记录",
    
        negative: "取消",
        neutral: "确定"
    })
        .on("neutral", clearTask)
       
        .show();
        function clearTask(){
            let mCachePath
            mCachePath = "/sdcard/Pictures/task"
            
            if(files.isDir(mCachePath)){
                files.removeDir(mCachePath+"/")
                toast("清除完成!")
               
            }else{
                toast("路径不存在")
            }
            todoList = []
            ui.todoList.setDataSource(todoList);
        }

})
/* todoList=[{content: "店铺名",state:"| 已完成",time:"| 07-02 12:25"},{content: "店铺名",state:"| 已完成",time:"| 07-02 12:25"},{content: "店铺名",state:"| 已完成",time:"| 07-02 12:25"},{content: "店铺名",state:"| 已完成",time:"| 07-02 12:25"},{content: "店铺名",state:"| 已完成",time:"| 07-02 12:25"},{content: "店铺名",state:"| 已完成",time:"| 07-02 12:25"},{content: "店铺名",state:"| 已完成",time:"| 07-02 12:25"}]
clearTask()

for (let i = 0; i < todoList.length; i++) {
   
    saveText("/sdcard/Pictures/task/task.txt",todoList[i].content+"|"+todoList[i].state.replace("| ","")+"|"+todoList[i].time.replace("| ",""))
}
function saveText(path,message){
    if(!files.isFile(path) ){
        files.createWithDirs(path)
    }
    files.append(path, message+"\n")
  
}
function clearTask(){
    let mCachePath
    mCachePath = "/sdcard/Pictures/task"
 
    if(files.isDir(mCachePath)){
        files.removeDir(mCachePath+"/")
    }
} */
// todoList = []
// Blist = readTxt("/sdcard/Pictures/task/task.txt")

// if(Blist){
    
//     for (let i = 0; i < Blist.length; i++) {
//         log(Blist[i])
//         mtodoList = {content: "",state:"| ",time:"| "}
//         AList = Blist[i].split("|")
//         if(AList.length == 3){
//             mtodoList.content = AList[0]
//             mtodoList.state ="| " + AList[1]
//             mtodoList.time ="| " + AList[2]
//             todoList.push(mtodoList)
//         }
//     }

// }
// new Date("")
// ui.todoList.setDataSource(todoList);
// ui.todoList.on("item_click", function (item, i, itemView, listView) {
//     log("点击了", i)
 
//     try {
//         if(lastitemView){
//             lastitemView.attr("bg","#ffffff") 
//             lastitemView = null
//         }
//     } catch (error) {
        
//     }
//     itemView.attr("background","#4169E1")
//     lastitemView = itemView
//     lastIndex = i
// });
var startime = Date.parse(new Date());//现行时间戳
//——————————————模块在下面————————————————


// var Edge=require('module.js');
var 主函数 = require("main_module.js");

//——————————————模块在上面————————————————
const storage = storageUI('UIConfigInfo')
// log(JSON.stringify(storage._storage))//查看本地存储信息
// log(files.read("/data/user/0/org.autojs.autojspro/shared_prefs/autojs.localstorage.UIConfigInfo11.xml"))
// storage.clear()
function storageUI(info) {
  let HoldUI, ViewGroup, storage = storages.create(info);
  events.on('exit', () => { HoldUI(1, ViewGroup) });
  let mTime = new Date().getTime();
  ui.view.getViewTreeObserver().addOnDrawListener({
    onDraw: function () {
        
      if (new Date().getTime() - mTime >= 500) {
        
        mTime = new Date().getTime();
        HoldUI(1, ViewGroup);
      }
    }
  });
  ui.post(HoldUI = function (flag, view) {
  
   
    let id
    (view = view || (ViewGroup = activity.getWindow().getDecorView().findViewById(android.R.id.content).getChildAt(0)))
      instanceof android.view.ViewGroup && Object.keys(Array.apply(null, new Array(view.childCount)))
        .forEach(i => {
          /(JsGridView|JsListView)/.test(view.getClass().getSimpleName()) ||
            HoldUI(flag, view.getChildAt(i));
        })
        
   
    if ((id = view.attr('id')) != null && (id = id.replace('@+id/', ''))) {
        moff = view.attr("checked") !== "off"
        mundefined = ((typeof storage.get(id)) != "undefined")
        switch (view.getClass().getSimpleName()) {
           
        case 'RadioButton': case 'CheckBox': /* 单选框|复选框|开关 case 'Switch':*/
          moff && flag ? storage.put(id, view.checked) : mundefined && view.setChecked(Boolean(storage.get(id))); break;
        case 'JsEditText':/* 输入框 */
          moff && flag ? storage.put(id, view.getText()) : mundefined && view.setText(storage.get(id)); break;
        case 'SeekBar':/* 进度条 */
          moff && flag ? storage.put(id, view.getProgress()) : mundefined && view.setProgress(Number(storage.get(id))); break;
        case 'JsSpinner':/* 下拉框 */
          moff && flag ? storage.put(id, view.getSelectedItemPosition()) : mundefined && view.setSelection(Number(storage.get(id))); break;
      }
    }
  });
  
  return storage;
}


ui.exitbut.click(function () {
    exit()
 })

 ui.start.click(function () {
  
  
    if (auto.service == null) {
        toast("请先开启无障碍服务！");
        return;
    } 
    if(ui.start.text()=="▶"){
        ScriptRunning = true
        // saveconfig();
        ui.start.setText("| |")
        startime = Date.parse(new Date())
        global.mThreadObj = threads.start(function () {  
            // saveconfig()
            //log(ui.ip_adress.text())
            //main();
     
            主函数.main("set1");
        

            
        }) 

    }else{
        log("Msg:正在停止中 请勿重复操作");
        global.mmmThreadObj =threads.start(function () {
            var yxtime = (Date.parse(new Date()) - startime) / 1000;
            yxtime = formatSeconds(yxtime);
            
            while(true){
                if(!global.OcrRunning){
                    ScriptRunning = false  
                    quitThread();
                    log("Msg:脚本停止")
                    break;
                }
            
            sleep(500)
            }

        })  
        global.mmmThreadObj.join()

        ui.start.setText("▶")
        
    }
    
 })
 /* paint = new Paint();
 paint.setColor(colors.RED);
 x = 0
 x1 = 200
 y = 0
 y1 = 100
 img = images.read("/sdcard/Pictures/Screenshots/qrcode.jpg")
 log(!!img)
 ui.board.on("draw", function(canvas) {
  
    canvas.drawColor(colors.WHITE)
    //canvas.drawBitmap(img, 5, 5, paint)
    //canvas.drawPicture(img)
    canvas.drawLine(x, y, x1, y1, paint)
}); */


function saveconfig() {
    
    Data.put("ip_adress", ui.ip_adress.text());
    Data.put("gLocalset", ui.gLocalset.checked);
    Data.put("gLocalReceipt", ui.gLocalReceipt.checked);
    Data.put("gTaskPath", ui.gTaskPath.text());
    Data.put("gPath", ui.gPath.text());
    Data.put("remarks", ui.remarks.text());
    Data.put("gPassword", ui.gPassword.text());
    Data.put("glinePath", ui.glinePath.text());
    Data.put("gLocalpay", ui.gLocalpay.checked);
    Data.put("gLocalpays", ui.gLocalpays.checked);
    Data.put("gLocaladd", ui.gLocaladd.checked);
    Data.put("gpaysNum", ui.gpaysNum.text());
    Data.put("gLocaltaobao", ui.gLocaltaobao.checked);
    Data.put("gLocallitetao", ui.gLocallitetao.checked);
    // Data.put("mOpenC", ui.mOpenC.checked);
    // Data.put("gtitle", ui.gtitle.text());
    // Data.put("gPass", ui.gPass.text());
    // Data.put("gMon", ui.gMon.text());
}

function readconfig() {
//   if(配置.get("isyh", "true")=="true"){
//     ui.check_yh.checked=true;
// }else{
//     ui.check_yh.checked=false;
// }
}
function formatSeconds(value) {
  var secondTime = parseInt(value);// 秒
  var minuteTime = 0;// 分
  var hourTime = 0;// 小时
  if (secondTime > 60) {
      minuteTime = parseInt(secondTime / 60);
      secondTime = parseInt(secondTime % 60);
      if (minuteTime > 60) {
          hourTime = parseInt(minuteTime / 60);
          minuteTime = parseInt(minuteTime % 60);
      }
  }
  var result = "" + parseInt(secondTime) + "秒";

  if (minuteTime > 0) {
      result = "" + parseInt(minuteTime) + "分" + result;
  }
  if (hourTime > 0) {
      result = "" + parseInt(hourTime) + "小时" + result;
  }
  return result;
}
function consoleshow() {
  importClass(Packages.androidx.recyclerview.widget.RecyclerView);
  console.show();
  let mConsoleView = getConsoleWindow();
  let parent = mConsoleView.parent;

  var inputView = parent.findViewById(context.getResources().getIdentifier("input", "id", context.getPackageName()));
  var buttonView = parent.findViewById(context.getResources().getIdentifier("submit", "id", context.getPackageName()));
  ui.run(function () {
      inputView.setVisibility(8);
      buttonView.setVisibility(8);
  });

  function getConsoleWindow() {
      var mConsole = runtime.console;
      let field = mConsole.class.superclass.getDeclaredField("mConsoleFloaty");
      field.setAccessible(true);
      mConsoleFloaty = field.get(mConsole);
      mConsoleView = mConsoleFloaty.getExpandedView();
      return mConsoleView;
  }

  let r = filterView(mConsoleView);
  function filterView(view, arr) {
      arr = arr || [];
      if (view instanceof android.view.ViewGroup) {
          arr.push(view);

          let childCount = view.childCount;
          for (var i = 0; i < childCount; i++) {
              let chileView = view.getChildAt(i);
              filterView(chileView, arr);
          }
      } else {
          arr.push(view);
      }
      return arr;
  }

  let num = 10;
  ui.run(function () {
      let recycleview = r[num];
      let adapter = recycleview.getAdapter();
      // r[num].setBackgroundColor(colors.parseColor("#2ed573"));
      function createAdapter() {
          let result = new JavaAdapter(
              Packages[adapter.getClass().getName()],
              {
                  onBindViewHolder: function (vh, i) {
                      adapter.onBindViewHolder(vh, i);
                      // vh.textView.setTextSize(10);
                      vh.textView.setTextColor(colors.parseColor("#2ed573"));
                  },
              },
              recycleview.parent.parent,
              null
          );
          return result;
      }
      let newAdapter = createAdapter();
      recycleview.setAdapter(newAdapter);
  });

}

events.on("exit", function () {
  //log("开始销毁模型")
 
 
});

function 取文本中间(str, a, b)  //取文本的中间值
{
    var w1 = str.indexOf(a);
    if (w1 < 0) {
        return false;
    };
    w1 = w1 + a.length;
    w2 = str.indexOf(b, w1);
    if (w2 <= 0) {
        return false;
    }
    return str.substr(w1, w2 - w1);
}//==============================悬浮代码====================================================
var 悬块 = function (window, view) {
    if (!window || !view) {
        throw "缺参数";
    };
    this.x = 0, this.y = 0;
    this.windowX, this.windowY;
    this.downTime = 500;
    this.Timeout = 0;
    this.Click = function () { };
    this.LongClick = function () { };
    this.setClick = function (fun) {
        //判断参数类型是否为函数？
        if (typeof fun == "function") {
            this.Click = fun;
        };
    };
    this.setLongClick = function (fun, ji) {
        //判断参数类型是否为函数？
        if (typeof fun == "function") {
            this.LongClick = fun;
            //判断参数是否可为设置数字？
            if (parseInt(ji) <= 1000) {
                this.downTime = parseInt(ji);
            };
        };
    };

    view.setOnTouchListener(new android.view.View.OnTouchListener((view, event) => {
        switch (event.getAction()) {
            //按下事件。
            case event.ACTION_DOWN:
                //按下记录各种坐标数据。
                this.x = event.getRawX();
                this.y = event.getRawY();
                this.windowX = window.getX();
                this.windowY = window.getY();
                //创建一个定时器用来定时执行长按操作。
                this.Timeout = setTimeout(() => {
                    this.LongClick();
                    this.Timeout = 0;
                }, this.downTime);
                return true;
            //移动事件。
            case event.ACTION_MOVE:
                //移动距离过大则判断为移动状态
                // if (Math.abs(event.getRawY() - this.y) > 5 && Math.abs(event.getRawX() - this.x) > 5) {
                //     //移动状态清除定时器
                //     if (this.Timeout) {
                //         //定时器存在则清除定时器。
                //         clearTimeout(this.Timeout);
                //         this.Timeout = 0;
                //     };
                //     //移动手指时调整悬浮窗位置
                //     window.setPosition(this.windowX + (event.getRawX() - this.x), this.windowY + (event.getRawY() - this.y));
                // };
                return true;
            //抬起事件。
            case event.ACTION_UP:
                if (this.Timeout) {
                    clearTimeout(this.Timeout);
                    this.Timeout = 0;
                    this.Click();
                };
                return true;
        };
        return true;
    }));
};

function xf() {
    //log("xf线程");
    // 如果悬浮窗不应该显示，则直接返回
    if (!global.mXFvisible) {
        return;
    }
    
    // 确保不重复创建线程
    if (global.mXF_ThreadObj && global.mXF_ThreadObj.isAlive()) {
        // 如果线程已存在且活跃，直接返回
        return;
    }
  
    global.mXF_ThreadObj = threads.start(function op() {
        // 创建主悬浮按钮
        var mainWindow = floaty.window(
            <frame>
                <card w="40" h="40" cardBackgroundColor="#4169E1" margin="0" cardElevation="5dp" 
                       gravity="center" alpha="0.9" cardCornerRadius="20dp">
                    <text id="mainBtn" w="*" h="*" textColor="#ffffff" 
                          padding="0" gravity="center" textSize="20sp" text="+" />
            </card>
            </frame>  
        );
        
        // 记录创建时间，用于稳定性检查
        let createTime = new Date().getTime();
        
        // 创建功能按钮菜单窗口（初始隐藏）
        var menuWindow = floaty.window(
            <frame>
                <vertical id="menuLayout" w="auto" h="auto" visibility="gone">
                    <card w="35" h="35" cardBackgroundColor="#4CAF50" margin="0 0 0 5" 
                           cardElevation="3dp" gravity="center" alpha="0.9" cardCornerRadius="17dp">
                        <text id="playBtn" w="*" h="*" textColor="#ffffff" 
                              padding="0" gravity="center" textSize="14sp" text="▶" />
                    </card>
                    <card w="35" h="35" cardBackgroundColor="#FF9800" margin="0 5 0 5" 
                           cardElevation="3dp" gravity="center" alpha="0.9" cardCornerRadius="17dp">
                        <text id="stopBtn" w="*" h="*" textColor="#ffffff" 
                              padding="0" gravity="center" textSize="14sp" text="■" />
                    </card>
                    <card w="35" h="35" cardBackgroundColor="#F44336" margin="0 5 0 0" 
                           cardElevation="3dp" gravity="center" alpha="0.9" cardCornerRadius="17dp">
                        <frame id="exitBtn" w="*" h="*" />
                    </card>
                </vertical>
            </frame>
        );
     
        // 设置窗口位置
        mainWindow.setPosition(device.width - 70, device.height * 0.5);
        menuWindow.setPosition(device.width - 67, device.height * 0.5 + 100);
        
        // 设置退出按钮图片
        ui.run(function() {
            try {
                // 使用项目根目录下的图标路径
                let exitIconPath = "./images/ic_exit.png";
                // 检查文件是否存在
                if(files.exists(exitIconPath)) {
                    // 创建ImageView来显示图标
                    let imgView = new android.widget.ImageView(context);
                    // 加载图片
                    let bitmap = android.graphics.BitmapFactory.decodeFile(files.path(exitIconPath));
                    // 设置图片
                    imgView.setImageBitmap(bitmap);
                    // 设置缩放类型为保持比例
                    imgView.setScaleType(android.widget.ImageView.ScaleType.FIT_CENTER);
                    // 设置padding让图标看起来小一些
                    imgView.setPadding(8, 8, 8, 8);
                    // 设置布局参数
                    let params = new android.widget.FrameLayout.LayoutParams(
                        android.view.ViewGroup.LayoutParams.MATCH_PARENT,
                        android.view.ViewGroup.LayoutParams.MATCH_PARENT
                    );
                    // 将图片视图添加到按钮中
                    menuWindow.exitBtn.addView(imgView, params);
                } else {
                    // 如果图片不存在，使用文本替代
                    let textView = new android.widget.TextView(context);
                    textView.setText("⏾");
                    textView.setTextSize(18);
                    textView.setTextColor(android.graphics.Color.WHITE);
                    textView.setGravity(android.view.Gravity.CENTER);
                    menuWindow.exitBtn.addView(textView);
                    log("退出图标未找到: " + files.path(exitIconPath));
                }
            } catch(e) {
                log("设置退出按钮图片出错: " + e);
            }
        });
        
        // 设置菜单显示状态和主按钮状态
        let isMenuVisible = false;
        let ScriptRun = false;
        
        // 添加主按钮点击事件
        var mainAd = new 悬块(mainWindow, mainWindow.mainBtn);
        mainAd.setClick(function() {
            isMenuVisible = !isMenuVisible;
            ui.run(function() {
                if (isMenuVisible) {
                    // 菜单显示时，主按钮变为X
                    mainWindow.mainBtn.setText("×");
                    menuWindow.menuLayout.setVisibility(View.VISIBLE);
                } else {
                    // 菜单隐藏时，主按钮变为+
                    mainWindow.mainBtn.setText("+");
                    menuWindow.menuLayout.setVisibility(View.GONE);
                }
            });
        });
        
        // 添加开始/暂停按钮点击事件
        var playAd = new 悬块(menuWindow, menuWindow.playBtn);
        playAd.setClick(function() {
            let pauseLockPath = "./pause.lock";
            let isPauseLockExists = files.exists(pauseLockPath);
            
            if(ScriptRunning) {
                // 脚本正在运行
                if(isPauseLockExists) {
                    // 存在锁文件，表示正在暂停状态，删除锁文件恢复运行
                    try {
                        files.remove(pauseLockPath);
                        //log("已删除暂停锁文件，恢复运行: " + files.path(pauseLockPath));
                        // 更新按钮状态为"暂停"
                        ui.run(function() {
                            menuWindow.playBtn.setText("| |");
                            menuWindow.playBtn.getParent().attr("cardBackgroundColor", "#E74C3C");
                        });
                    } catch(e) {
                        log("删除暂停锁文件出错: " + e);
                    }
                } else {
                    // 不存在锁文件，表示正在运行状态，创建锁文件暂停
                    try {
                        files.createWithDirs(pauseLockPath);
                        //log("已创建暂停锁文件，暂停运行: " + files.path(pauseLockPath));
                        // 更新按钮状态为"播放"
                        ui.run(function() {
                            menuWindow.playBtn.setText("▶");
                            menuWindow.playBtn.getParent().attr("cardBackgroundColor", "#4CAF50");
                        });
                    } catch(e) {
                        log("创建暂停锁文件出错: " + e);
                    }
                }
            } else {
                // 脚本未运行，点击启动
                ui.start.click();
                // 确保没有暂停锁文件
                try {
                    if(isPauseLockExists) {
                        files.remove(pauseLockPath);
                        //log("已删除暂停锁文件: " + files.path(pauseLockPath));
                    }
                } catch(e) {
                    log("删除暂停锁文件出错: " + e);
                }
            }
            
            // 点击后自动隐藏菜单
            ui.run(function() {
                isMenuVisible = false;
                mainWindow.mainBtn.setText("+");
                menuWindow.menuLayout.setVisibility(View.GONE);
            });
        });
        
        // 添加停止按钮点击事件
        var stopAd = new 悬块(menuWindow, menuWindow.stopBtn);
        stopAd.setClick(function() {
            // 如果脚本正在运行，执行停止操作
            if (ScriptRunning) {
                ui.start.click(); // 暂停当前运行
                // 这里可以添加其他停止逻辑
                toastLog("已停止任务");
            } else {
                toastLog("当前没有运行中的任务");
            }
            
            // 点击后自动隐藏菜单
            ui.run(function() {
                isMenuVisible = false;
                mainWindow.mainBtn.setText("+");
                menuWindow.menuLayout.setVisibility(View.GONE);
            });
        });
        
        // 添加退出按钮点击事件
        var exitAd = new 悬块(menuWindow, menuWindow.exitBtn);
        exitAd.setClick(function() {
            // 弹出确认对话框
            dialogs.build({
                title: "确认退出",
                content: "是否退出应用？",
                positive: "确定",
                negative: "取消"
            }).on("positive", function() {
                // 关闭所有悬浮窗
                floaty.closeAll();
                // 退出应用
                exit();
            }).on("negative", function() {
                // 点击取消后只隐藏菜单
                ui.run(function() {
                    isMenuVisible = false;
                    mainWindow.mainBtn.setText("+");
                    menuWindow.menuLayout.setVisibility(View.GONE);
                });
            }).show();
        });
        
        // 添加定时器检查悬浮窗显示状态
        setInterval(function () {
            // 检查ScriptRunning状态更新按钮
            ScriptRun = ScriptRunning;
            
            // 检查悬浮窗显示状态
            if(!global.mXFvisible) {
                // 如果不应该显示悬浮窗，则关闭所有悬浮窗
                ui.run(function () {
                    try {
                        if(mainWindow) mainWindow.close();
                        if(menuWindow) menuWindow.close();
                    } catch(e) {
                        log("关闭悬浮窗出错: " + e);
                    }
                });
                // 结束当前线程
                threads.currentThread().interrupt();
                return;
            }
            
            // 检查悬浮窗是否仍然存在
            let currentTime = new Date().getTime();
            let windowExists = true;
            
            try {
                // 尝试访问悬浮窗属性，如果悬浮窗已关闭会抛出异常
                windowExists = mainWindow && mainWindow.isShowing();
            } catch(e) {
                windowExists = false;
            }
            
            // 如果悬浮窗已关闭但应该显示，且悬浮窗线程运行超过2秒，重新创建悬浮窗
            if(!windowExists && global.mXFvisible && (currentTime - createTime > 2000)) {
                // 中断当前线程
                threads.currentThread().interrupt();
                // 重新创建悬浮窗
                setTimeout(function() {
                    xf();
                }, 200);
                return;
            }
            
            ui.run(function () {
                if(global.mXFvisible){
                    // 如果之前已关闭，现在需要显示，则不执行closeAll
                    // 更新开始/暂停按钮状态
                    if(ScriptRun){
                        menuWindow.playBtn.setText("| |");
                        menuWindow.playBtn.setTextColor(colors.parseColor("#FFFFFF"));
                        menuWindow.playBtn.getParent().attr("cardBackgroundColor", "#E74C3C");
                    } else {
                        menuWindow.playBtn.setText("▶");
                        menuWindow.playBtn.setTextColor(colors.parseColor("#FFFFFF"));
                        menuWindow.playBtn.getParent().attr("cardBackgroundColor", "#4CAF50");
                    }
                } else {
                    // 如果不应该显示悬浮窗，则关闭
                    floaty.closeAll();
                }
            });  
        }, 500);
    })
    
    //创建一个新的悬浮控制模块 ad 并带入参数(所要控制的悬浮窗和用来控制悬浮窗移动的控件)。
}

var window  // 创建弹窗变量 / 对象
var str = "当前成功: 0"+"   失败: 0";
var str1 = "TB tomato";
var consoleH = device.height*0.35

var Maple = {};
Maple.ConSole = function () {
    let resource = context.getResources();
    ConSole = floaty.rawWindow(
        <relative id="consoles">
            <vertical w="*">
                <text w="auto" h="auto" textSize="14" margin="8 0 20 0" id="Maple ALOS" textColor="#2F4F4F" text="{{str1}}" />
                <card id="indx2" w="*" margin="0 0 0 1" h="*" background="#161824" cardCornerRadius="3" cardElevation="2dp" gravity="center_vertical" alpha="0.6"  >
                    <text id="wz" textColor="#FFFFFFFF" textSize="12" textStyle="bold" text="{{str}}" textIsSelectable="true" maxliness="1" />
                </card>
                <vertical w="*" h="*" background="#000000" textSize="4"  alpha="0.6">
                    <com.stardust.autojs.core.console.ConsoleView id="console" />
                </vertical>
            </vertical>
        </relative>
    );
    ConSole.setTouchable(false);    
    ConSole.setPosition(0, device.height*0.6);
    ConSole.setSize(device.width, device.height*0.4);
    ConSole.console.setConsole(runtime.console);
    let c = new android.util.SparseArray();
    let Log = android.util.Log;
    c.put(Log.VERBOSE, new java.lang.Integer(colors.parseColor("#55deee")));
    c.put(Log.DEBUG, new java.lang.Integer(colors.parseColor("#ffffffff")));
    c.put(Log.INFO, new java.lang.Integer(colors.parseColor("#ff64dd17")));
    c.put(Log.WARN, new java.lang.Integer(colors.parseColor("#ff2962ff")));
    c.put(Log.ERROR, new java.lang.Integer(colors.parseColor("#ffd50000")));
    c.put(Log.ASSERT, new java.lang.Integer(colors.parseColor("#ffff534e")));
    // importClass(Packages.androidx.recyclerview.widget.RecyclerView);
    // console.show();
    // let mConsoleView = getConsoleWindow();
    let parent = ConSole.console.parent;
  
    var inputView = parent.findViewById(context.getResources().getIdentifier("input", "id", context.getPackageName()));
    var buttonView = parent.findViewById(context.getResources().getIdentifier("submit", "id", context.getPackageName()));
    ui.run(function () {
        inputView.setVisibility(8);
        buttonView.setVisibility(8);
    });

    function getResourceID(name, defType) {
        return resource.getIdentifier(name, defType, context.getPackageName());
    };
    setInterval(function () {
        // let Maple_time = runTime();
        // if (Maple_time) {
        //     try {
        //         if (Maple_time) ui.run(() => ConSole.time.text(Maple_time));
        //     } catch (error) { }
        // }
    }, 1000);
}
Maple.Logss = function (msg) {
    console.verbose("[" + format(new Date().getTime(), 'hh:ii:ss') + "] " + msg); //自定义带时间log
}
Maple.close = function () {
    try {
        ConSole.close(); //关闭控制台
    } catch (error) {
      
    }
  
}
Maple.clear = function () {
    console.clear(); //清空控制台
}


 //================================= 自定义代码 ====================================
//结束子线程
function quitThread(){
    if(global.mTC_ThreadObj.isAlive()){
        //关闭子线程自身
        global.mTC_ThreadObj.interrupt();
    }
    if(global.mThreadObj.isAlive()){
        //关闭脚本主线程线程自身
        global.mThreadObj.interrupt();
    }
    if(global.mHeardThreadObj.isAlive()){
        //关闭脚本主线程线程自身
        global.mHeardThreadObj.interrupt();
    }
 
    sleep(500)
    var mx=0
    while(true){
            //判断子线程是否存在，若存在则关闭子线程及对应的定时器
        if(global.mTC_ThreadObj.isAlive()){
            //关闭子线程自身
            global.mTC_ThreadObj.interrupt();
        }else if(global.mHeardThreadObj.isAlive()){
            //关闭脚本主线程线程自身
            global.mHeardThreadObj.interrupt();
        }else if(global.mThreadObj.isAlive()){
            //关闭脚本主线程线程自身
            global.mThreadObj.interrupt();
        }else{
            break;
        }
        sleep(500);
    }
}
function DexClassLoader(dexPath) {
    return new Packages.dalvik.system.DexClassLoader(dexPath, new Utils().getCacheDir(), null, context.getClassLoader());
    }
function Utils() {
importClass(android.os.Environment);

function hasExternalStorage() {
    return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
/**
 * 获取缓存路径
 * @return 返回缓存文件路径
 */
this.getCacheDir = function () {
    let cache;
    if (hasExternalStorage()) {
    cache = context.getExternalCacheDir();
    } else {
    cache = context.getCacheDir();
    }
    if (!cache.exists()) cache.mkdirs();
    return cache;
};
}

function 取文本右边(str, a)  //取文本的中间值
{
    var w1 = str.indexOf(a);
    if (w1 < 0) {
        return false;
    };
    w1 = w1 + a.length;
    w2 = str.length;
    return str.substr(w1, w2 - w1);
}
function readTxt(path){
    let mlist = []
    let glines 
    let mline,mcontent
    try {
        glines = files.read(path)
    } catch (error) {
        toastLog("文件不存在")
        return false;
    }
    try {
               
        // log(glines)
        if(glines){
            glines = glines.split("\n");
            return glines;
          
        }
    } catch (error) {
        toastLog("导入失败",error)
        
    }
    return false;
}


app.sendBroadcast({
    action: "CloudControl.restart.app",
  });


  // 检查登录状态并初始化适当的界面
  checkLoginStatus();

// 根据登录状态初始化悬浮窗部分已在checkLoginStatus函数中处理
// 移除这段代码避免重复调用xf()
/* if(global.mXFvisible) {
  // 如果已登录，则显示悬浮窗
  xf();
} */

// 添加mStart复选框的点击事件处理，防止它影响悬浮窗
ui.mStart.on("click", function() {
    // 强制设置为不选中，以避免用户勾选此框导致悬浮窗隐藏
    ui.mStart.checked = false;
    // 显示一条提示
    toast("已弃用此选项，悬浮窗将保持显示");
});